package com.chengyu.core.util.dingding;

import com.chengyu.core.util.NewRedisUtils;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 钉钉推送工具类
 */
@Slf4j
@Async
@Component
public class DingTalkPushUtil {

    // 1. 填入appid
    @Value("${apiUrl.dingding.pushText}")
    private String pushTextUrl;

    @Value("#{'${apiUrl.dingding.mobiles:}'.split(',')}")
    private List<String> mobiles;

    @Autowired
    private NewRedisUtils redisUtils;

    final String key = "dingDing:pushText:count:";

    /**
     * 按照钉钉API处理内容格式
     * 调用频率限制
     * 由于消息发送太频繁会严重影响群成员的使用体验，因此钉钉开放平台对自定义机器人发送消息的频率作出以下限制：
     * 每个机器人每分钟最多发送20条消息到群里，如果超过20条，会限流10分钟。
     *
     * @param content
     */
    public void pushMsg(String content) {
        try {
            int pushCount = 0;
            Object object = redisUtils.get(key);
            if (object != null) {
                pushCount = Integer.parseInt(object.toString());
                if (pushCount >= 20) {
                    log.error("钉钉消息，调用频率超出限制");
                    return;
                }
            }
            DingTalkClient client = new DefaultDingTalkClient(pushTextUrl);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("减排场景:" + content);
            request.setText(text);
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setAtMobiles(mobiles);
            // isAtAll类型如果不为Boolean，请升级至最新SDK
            at.setIsAtAll(false);
            request.setAt(at);

            //link
//        request.setMsgtype("link");
//        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
//        link.setMessageUrl("https://www.dingtalk.com/");
//        link.setPicUrl("");
//        link.setTitle("时代的火车向前开");
//        link.setText("这个即将发布的新版本，创始人xx称它为红树林。而在此之前，每当面临重大升级，产品经理们都会取一个应景的代号，这一次，为什么是红树林");
//        request.setLink(link);

            //markdown
//        request.setMsgtype("markdown");
//        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
//        markdown.setTitle("杭州天气");
//        markdown.setText("#### 杭州天气 @156xxxx8827\n" +
//                "> 9度，西北风1级，空气良89，相对温度73%\n\n" +
//                "> ![screenshot](https://gw.alicdn.com/tfs/TB1ut3xxbsrBKNjSZFpXXcXhFXa-846-786.png)\n"  +
//                "> ###### 10点20分发布 [天气](http://www.thinkpage.cn/) \n");
//        request.setMarkdown(markdown);
            OapiRobotSendResponse response = client.execute(request);
            if (response.isSuccess()) {
                ++pushCount;
                redisUtils.set(key, pushCount, 60);
                log.info(">>>>>>>>>钉钉发送成功..........<<<<<<<<<");
            } else {
                log.error(">>>>>>>>>钉钉发送失败..........<<<<<<<<<--{}", response);
            }
        } catch (ApiException e) {
            log.error(">>>>>>>>>钉钉发送失败..........<<<<<<<<<--{}", e);
        }
    }
}

